//
//  WBHomeViewModel.swift
//  WB123
//
//  Created by xuyunde mac pro on 2017/7/4.
//  Copyright © 2017年 NSObjiect. All rights reserved.
//

import UIKit
import SDWebImage
/*
 --帮助首页请求数据,保存数据,提供数据
 */
class WBHomeViewModel: NSObject {

    // 保存首页数组模型
    lazy var dataList:[WBStatusViewModel] = [WBStatusViewModel]()
}

extension WBHomeViewModel{
    
    func getHomeData(isPullUp: Bool, finish:@escaping (Bool, Int)->()){
        
        // since_id 为下拉刷新服务
        // max_id 为上拉加载更多服务
        
        var maxId:Int64 = 0
        var sinceId:Int64 = 0
        
        // 判断如果是下拉刷新
        if !isPullUp {
            sinceId = dataList.first?.homeModel?.id ?? 0
        }else{
            // 上拉加载更多
            maxId = dataList.last?.homeModel?.id ?? 0
            //若指定此参数,则返回ID小于或者等于maxid的微博,默认0
            if maxId > 0 {
                maxId -= 1
            }
        }
        
        WBNetworkTools.share.homeLoadData(since_id: sinceId, max_id: maxId, success: { (response) in
            //            print("请求成功",response)
            // 判断是否为nil和字典
            guard let resDict = response as? [String: Any] else {
                finish(false, 0)
                return
            }
            // 判断
            guard let reslist = resDict["statuses"] as? [[String: AnyObject]] else {
                finish(false, 0)
                return
            }
            let tempList = NSArray.yy_modelArray(with: WBHomeModel.self, json: reslist)
            
            guard let t = tempList as? [WBHomeModel] else{
                finish(false, 0)
                return
            }
            // 创建一个临时数组 ->WBStatusViewModel
            var tempStatusList: [WBStatusViewModel] = [WBStatusViewModel]()
            
            //创建调度组
            let group = DispatchGroup()
            // 遍历保存模型数组 t
            for homeModel in t {
                
                // 下载单张图片
                if homeModel.pic_urls?.count == 1{
                    group.enter()
                    SDWebImageManager.shared().loadImage(with: URL(string: homeModel.pic_urls?.first?.thumbnail_pic ?? ""), options: [], progress: nil, completed: { (_, _, _, _, _, _) in
                        print("原创微博图片下载完成")
                        group.leave()
                    })
                }
                if homeModel.retweeted_status?.pic_urls?.count == 1{
                    
                    group.enter()
                    SDWebImageManager.shared().loadImage(with: URL(string: homeModel.retweeted_status?.pic_urls?.first?.thumbnail_pic ?? ""), options: [], progress: nil, completed: { (_, _, _, _, _, _) in
                        print("转发微博图片下载完成")
                        group.leave()
                    })
                }
                
                // 创建viewModel
                let statusViewModel = WBStatusViewModel()
                //赋值
                statusViewModel.homeModel = homeModel
                //保存
                tempStatusList.append(statusViewModel)
            }
            // 赋值
//            self.dataList = tempStatusList
            // 下拉刷新
            if !isPullUp{
                self.dataList = tempStatusList + self.dataList
                
            }else{
                // 上拉加载更多
                self.dataList =  self.dataList + tempStatusList
            }
            
            // 执行成功
//            finish(true)
            // 使用调度组来监听单张图片是否下载完成
            group.notify(queue: DispatchQueue.main, execute: { 
                print("所以单张图片下载完成")
                finish(true, tempStatusList.count)
            })
        }) { (error) in
            // 请求失败
            print("请求失败",error)
            finish(false, 0)
        }

    }
}
